import math, gtk, Point, Shape


class DrawingController:
	
	def __init__(self, drawing_area):
		self.all_shapes = [] # all the shapes to br draw
		self.drawing_area = drawing_area	
		self.shape_finished = True
		
	def draw(self, spec,save):
		""" Take a specification Spec to know which shape to add to self.all_shapes"""
		if spec.shape == "Line":
			self.shape = Shape.Line(spec.points[0], spec.points[1], self.drawing_area.window, spec)	
		elif spec.shape == "Circle":
			self.shape = Shape.Circle(spec.points[0], spec.points[1], self.drawing_area.window, spec, save)
		elif spec.shape == "Polygon":
			if self.shape_finished:
				self.shape = Shape.Polygon(spec.points[-2], spec.points[-1], self.drawing_area.window, spec)
			else:
				self.shape.add_point(spec.points[-1], save)

		self.repaint()
		self.shape_finished = self.shape.draw()
		if(save and self.shape.finished):
			self.all_shapes.append(self.shape)
		return self.shape_finished


	def save_shapes(self):
		arq = open("save.txt","a")
		for s in self.all_shapes:
			s.print_spec(arq)
		arq.close()
	
	def clear_all(self):
		""" Clear the dwaing_area """
		self.all_shapes = []
		self.shape_finished = True
		self.repaint()

	def fill_all(self,spec):
		gc = self.drawing_area.window.new_gc()
		(red,green,blue) = (65535*x for x in spec.color)
		gc.set_rgb_fg_color(gtk.gdk.Color(red,green,blue))
	  	for s in self.all_shapes:
			s.fill(gc)
		self.repaint()

	def clear_screen(self):
		gc = self.drawing_area.window.new_gc()
		gc.set_rgb_fg_color(gtk.gdk.Color(65535,65535,65535))
		self.drawing_area.window.draw_rectangle(gc, True, 0, 0, 500, 400) # acochambrado
	
	def repaint(self):
		""" Repaint all_shapes in drawing_area """
		self.clear_screen()
		for s in self.all_shapes:
			s.draw()
		
